const { tmppath, apiDist, rest,typeService } = require('../conf');
const {join,sep} = require('path');
const {formatParam,formatResult,formatName} = require('./api2Type');

const fs = require('fs');

const apiSrc = join(tmppath,'/api');

const createPath = {};
function mkdir(pathStr){
  if(createPath[pathStr])return;
  if(fs.existsSync(pathStr)){
    createPath[pathStr]=true;
    return;
  }

  const p = pathStr.split(sep);
  let i;
  for(i=p.length-1;i>0;i--){
    if(fs.existsSync(p.slice(0,i).join(sep))){
      break;
    }
  }
  for(let j=i+1;j<=p.length;j++){
    fs.mkdirSync(p.slice(0,j).join(sep));
  }
  createPath[pathStr]=true;
}


const files = Object.keys(rest);
const analyFiles = {};
files.forEach(m=>{
  analyFiles[join(apiSrc,sep+m.replace(/\./g,sep))] = {reg:files[m]==null?/[\s\S]*/:new RegExp(
    `(^${(typeof files[m]=='string'?[files[m]]:files[m]).join('$)|(^')}$)`.replace(/\{/g,'\\{').replace(/\}/g,'\\}'),'i'
  ),dist:join(apiDist,sep+m.replace(/\./g,sep)+'.ts')};
  mkdir(join(apiDist,m.replace(/\.[^.]+$/,'').replace(/\./g,sep)));
});

function start(){
  Object.keys(analyFiles).forEach(m=>{
    const req = require(m);
    let oneFile = [typeService.header];
    req.forEach(node=>{
      if(!analyFiles[m].reg.test(node.url)){
        return;
      }
      const urlName = formatName(node.url.replace(/\{|\}/g,''));
      const params = formatParam(node.params);
      const result = formatResult(node.result);
      const type = node.action.toUpperCase();
      oneFile.push(typeService.req({params,result,actionType:type,urlName,url:node.url}));
    });
    fs.writeFileSync(analyFiles[m].dist,oneFile.join('\n'),(err)=>{
      if(err){
        console.error('服务生成失败:',analyFiles[m].dist)
        return;
      }
      console.log('服务生成成功:',analyFiles[m].dist)
    })
  })
  //TODO:如果有手动定义的typescript,则进行拷贝
}

start();